import { setItem, getItem, removeItem } from "@/utils/storage";
import { submitExam } from "@/api";
import router from "@/router";
import {  Message } from 'element-ui'


export default {
  namespaced: true,
  state: () => ({
    // 剩余时间
    time: getItem("time") || 0,
    // 倒计时定时器
    timeDown: null,
    // 答案列表
    answerList: getItem("answerList") || [],
    // 当前考试试卷id
    currentID: getItem("currentID") || "",
  }),
  mutations: {
    // 设置总时长
    setTime(state, time) {
      if (state.time === 0) {
        state.time = time * 3600 * 1000;
      }
      setItem("time", time);
      this.commit("exam/setTimeDown");
    },
    // 设置倒计时
    setTimeDown(state) {
      if (state.timeDown === null) {
        state.timeDown = setInterval(() => {
          if (state.time === 0) {
            Message({
              message: "考试结束",
              type: 'success'
            })
            this.dispatch("exam/endExam");
            return;
          }
          state.time -= 1000;
          setItem("time", state.time);
        }, 1000);
      }
    },
    // 设置当前考试试卷id
    setID(state, id) {
      state.currentID = id;
      setItem("currentID", state.currentID);
    },
    // 设置答案列表
    setAnswerList(state, answerList) {
      state.answerList = answerList;
      setItem("answerList", answerList);
    },
    // 清空缓存
    clearData(state) {
      clearInterval(state.timeDown);
      state.timeDown = null;
      state.time = 0;
      state.answerList = [];
      state.currentID = "";
      removeItem("time");
      removeItem("answerList");
      removeItem("currentID");
    },
  },
  actions: {
    // 开始倒计时
    startExam(context, time) {
      this.commit("exam/setTime", time);
    },

    // 结束考试
    endExam(context) {
      // console.log(this);
      this.dispatch("exam/submit", {
        answer: this.state.exam.answerList,
        paperid: this.state.exam.currentID,
      }).then((data) => {
        router.push("/");
      })
      // this.commit("exam/clearData")
    },

    // 提交试卷
    submit(context, data) {
      // console.log(this);
      submitExam(data);
      this.commit("exam/clearData");
    },
  },
};
